package com.longjiyi.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 移动零 {
    public static void main(String[] args) {
        int[] ints = new int[5];
        ints[0] = 0;
        ints[1] = 1;
        ints[2] = 0;
        ints[3] = 3;
        ints[4] = 12;
        moveZeroes(ints);
    }

    public static void moveZeroes(int[] nums) {
        List<Integer> arrayList = new ArrayList<>();
        // 记录0的数量
        int zeroCount = 0;
        // 将非0的数加入arrayList，记录0的数量
        for (int num : nums) {
            if (num != 0) {
                arrayList.add(num);
            } else {
                zeroCount++;
            }
        }
        // 在arrayList末尾添加相应数量的0
        for (int i = 0; i < zeroCount; i++) {
            arrayList.add(0);
        }
        // 将ArrayList转为int[]并赋值回nums
        for (int i = 0; i < nums.length; i++) {
            nums[i] = arrayList.get(i);
        }
    }
}
